package com.huonan.component.thread;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * 线程池
 */
public final class ExecutorPool {
    public static ExecutorService getExecutorService(int size) {
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("thread-pool-%d").build();

        //Common Thread Pool
        return new ThreadPoolExecutor(size, size,
                10L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
    }

    /**
     * 优雅关闭线程池
     * @param threadPool 线程
     */
    public static void closePool(ExecutorService threadPool) {
        threadPool.shutdown();
        if (threadPool.isTerminated()) {
            Thread.yield();
        }
    }
}